//
//  MailDetailsVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/12.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "MailDetailsVC.h"
#import "MailDetailsHeadView.h"
#import "MailCell.h"
#import "MailNameCell.h"
#import "MailSelectorColorCell.h"
#import "MailSelectoStoreCell.h"
#import "MailGoodsContentCell.h"
#import "MailBottomView.h"
#import "MailSelectoColorClassView.h"
#import "MailConfirmOrderVC.h"
#import "MailDetailsAlreadyAbulkCell.h"
#import "MailDetailsAddAbulkCell.h"
#import "MailDetailsAddAbulkHeadView.h"
#import "MailDetailsAddBulkView.h"
#import "AbulkDetailsVC.h"
#import "MailGoodsAttributeModel.h"
#import "PagingViewController.h"
#import "UserSetingVC.h"
#import "BusinessDetailedVC.h"
#import "ShoppingCartModel.h"
#import "ShareView.h"
#import "NewShareView.h"
#import "GoodsPostersShareView.h"



extern UserModel *userModel;
@interface MailDetailsVC ()<UIWebViewDelegate>

@property (nonatomic,strong) MailDetailsHeadView *headView;
@property (strong, nonatomic)MailBottomView *bottomView;
@property (strong, nonatomic)MailSelectoColorClassView *selectoColorClassView;
@property (strong, nonatomic)MailDetailsAddBulkView *addAbulkView;
@property (strong, nonatomic)NSArray *goodsAttrubuteArray;
@property (strong, nonatomic)NSMutableArray *selectGoodAttributeArray;
@property (strong, nonatomic)MailSelectorColorCell *twoCell;
@property (strong, nonatomic)MailGoodsContentCell *contentCell;
@property (assign, nonatomic)float contentCellHeight;
@property (assign, nonatomic)BOOL isBuyBtnClick;//是否立即购买
@property (assign, nonatomic)BOOL isStartPt;//是否开团
@property (assign, nonatomic)BOOL isAddPt;//是否参团
@property (assign, nonatomic)BOOL isShoppingCar;//是否购物车
@property (assign, nonatomic)BOOL isRefreshGoodsAttrubuteArray;
@property (strong, nonatomic)UIWindow *wind;
@property (strong, nonatomic)NSMutableArray *availableSkuAtt;

@end

@implementation MailDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.defaultStartPage = 1;
    self.title = @"商品详情";
    [self creatTableViewWithCellIdentity:@"MailNameCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailSelectorColorCell" bundle:nil] forCellReuseIdentifier:@"MailSelectorColorCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailSelectoStoreCell" bundle:nil] forCellReuseIdentifier:@"MailSelectoStoreCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailGoodsContentCell" bundle:nil] forCellReuseIdentifier:@"MailGoodsContentCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailDetailsAlreadyAbulkCell" bundle:nil] forCellReuseIdentifier:@"MailDetailsAlreadyAbulkCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MailDetailsAddAbulkCell" bundle:nil] forCellReuseIdentifier:@"MailDetailsAddAbulkCell"];
    
    self.view.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.estimatedRowHeight = 135;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, NavBarHeight, kScreenW, kScreenH-NavBarHeight -NeedStatusViewHeight-49);
    self.tableView.tableHeaderView = self.headView;
    
    UIView *footer = [[UIView alloc]init];
    footer.frame = CGRectMake(0, 0, KSCREEN_WIDTH, 15);
    footer.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.tableFooterView = footer;
    self.contentCellHeight = 50;
    [self.view addSubview:self.bottomView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setTableViewCellHight:)  name:@"getCellHightNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(abulkDetailsUpDate)  name:kUserAbulkDetailsUpDate object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestData)  name:kUserGoodsDetailsUpDate object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareSuccess)  name:kShareSuccess object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareFailure)  name:kShareFailure object:nil];
    
    
    self.isRefreshGoodsAttrubuteArray = YES;
    [self setRefresh];
    SVPShowInternetWaiting
    [self requestData];
}


- (void)shareSuccess {
    
    SVP(@"分享成功");
}

- (void)shareFailure {
    
    SVP(@"分享失败");
}
 

#pragma mark - 团购商品结束
- (void)abulkDetailsUpDate {
    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"当前商品已结束售卖!" preferredStyle:UIAlertControllerStyleAlert];

    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        [self.navigationController popViewControllerAnimated:YES];
       
    }]];
    
}

-(void)setTableViewCellHight:(NSNotification *)info
{
    NSDictionary * dic=info.userInfo;
    //判断通知中的参数是否与原来的值一致,防止死循环
    if (self.contentCellHeight != [[dic objectForKey:@"height"]floatValue])
    {
        self.contentCellHeight= [[dic objectForKey:@"height"]floatValue];
        if (self.contentCellHeight < 50) {
            
            self.contentCellHeight = 50;
        }
        
        [self.tableView reloadData];
    }
}


- (void)requestData
{
    NSString *url = @"sku/queryGoodsInfo";
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:self.goodsModel.sku_id forKey:@"sku_id"];
    if (self.goodsModel.sku_type == 2  || self.goodsModel.sku_type ==9) {
        url = @"sku/queryTgGoodsInfo";
    }
    if (self.goodsModel.is_yk == 2) {
        url = @"sku/queryGoodsInfo";
    }
    if ([url isEqualToString:@"sku/queryGoodsInfo"]) {
        [para setObject:@(self.goodsModel.is_pt) forKey:@"is_pt"];
    }
    
    
    WeakSelf(ws)
    [NetRequestTool postUrl:url parameters:para success:^(id responseObject) {
        ws.goodsDetailsModel = [MailGoodsDetailsModel mj_objectWithKeyValues:responseObject[@"object"]];
        if ([CommonTTool isStrNull:ws.goodsDetailsModel.state]) {
            [self.navigationController popViewControllerAnimated:YES];
            SVP(@"该商品已下架");
        }
        ws.headView.model = ws.goodsDetailsModel;
        ws.selectoColorClassView.model = ws.goodsDetailsModel;
        if (ws.goodsDetailsModel.sku_type != 3  && ws.goodsDetailsModel.sku_type != 9) {
            if (self.isRefreshGoodsAttrubuteArray) {
                [ws  querySkuAttribute];

            }
//            [ws  querySkuAttribute];

            self.isRefreshGoodsAttrubuteArray = NO;
            self.selectGoodAttributeArray = [self.goodsDetailsModel.gg_info componentsSeparatedByString:@"|"];
            
        }

        
       
        
        if (ws.goodsDetailsModel.sku_type == 3 || ws.goodsDetailsModel.sku_type == 9) {
            [self.bottomView.addShoppingCartBtn setHidden:YES];
            self.bottomView.buyBtn.layer.cornerRadius = 5;
            self.bottomView.buyBtn.clipsToBounds = YES;
        }
        
        [ws.tableView reloadData];
        if (![CommonTTool isStrNull:self.goodsDetailsModel.pt_group_list] && ![CommonTTool isStrNull:self.tg_group_id]) {
            for (pt_group_listModel *model in self.goodsDetailsModel.pt_group_list) {
                if ([model.tg_group_id isEqualToString:self.tg_group_id]) {
                    if (self.goodsDetailsModel.stock <= 0) {
                              SVP(@"当前商品已经没有库存了");
                              return;
                       }

                       self.addAbulkView.model = model;
                       [self showAddAbulkView];
                }
            }
        }

        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        SVPDismiss
        [ws endRefreshNoMoreData];
    }];
    

}
    

- (MailDetailsHeadView *)headView {
    
    if (!_headView) {
        _headView = [[NSBundle mainBundle] loadNibNamed:@"MailDetailsHeadView" owner:self options:nil].lastObject;
        _headView.frame = CGRectMake(0, 0, kScreenW, 433);
        
        
//        [_headView.startAbulkBtn addTarget:self action:@selector(showAddAbulkView) forControlEvents:UIControlEventTouchUpInside];
        [_headView.startAbulkBtn addTarget:self action:@selector(openGroupClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _headView;
    
}

#pragma mark - 我要开团（需要判断）
- (void)openGroupClick {
    
   
    if (![CommonTTool isJumpLoginVC:YES]) {
        
        return;
    }
    if (![CommonTTool isVipShow:YES]) {
        
        return;
    }
    

    
    if (self.goodsDetailsModel.stock <= 0) {
        SVP(@"当前商品已经没有库存了");
        return;
    }
    self.isBuyBtnClick = NO;
    self.isShoppingCar = NO;
    self.isStartPt = YES;
    self.isAddPt = NO;
    self.selectoColorClassView.nextBtn.hidden = NO;
    self.selectoColorClassView.twoBgView.hidden = YES;
    [self showSelectorColorView];
    
}




- (MailBottomView *)bottomView {
    
    if (!_bottomView) {
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"MailBottomView" owner:self options:nil].lastObject;
        _bottomView.frame = CGRectMake(0, KSCREEN_HEIGHT -49 -NeedStatusViewHeight, kScreenW, 49);
        [_bottomView.addShoppingCartBtn addTarget:self action:@selector(addShoppingCartBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.buyBtn addTarget:self action:@selector(buyBtnClick) forControlEvents:UIControlEventTouchUpInside];
        UITapGestureRecognizer *phoneTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(phoneTapClick)];
        [_bottomView.phoneView addGestureRecognizer:phoneTap];
        
        UITapGestureRecognizer *shareTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shareTapClick)];
        [_bottomView.shareView addGestureRecognizer:shareTap];
        
    }
    
    return _bottomView;
    
}

#pragma mark - 分享
- (void)shareTapClick {
    
    ShareView *share =  [ShareView showCodeView];
    share.buttonClick = ^(NSInteger tag) {
        switch (tag) {
            case 101:
            {
                [self shareType:0];
            }
                break;
            case 102:
            {
                 [self shareType:1];
            }
                break;
            case 103:
            {
                [self weiboShare];
            }
                break;
            case 104:
            {
                GoodsPostersShareView*shareView = [GoodsPostersShareView showView];
                shareView.model = self.goodsDetailsModel;
                shareView.dataString = [self getShareURL];
                

            }
                break;
            case 105:
            {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                
                
                pasteboard.string = [self getShareURL];

                SVP(@"链接已复制");
                 
            }
                break;
            default:
                break;
        }
        
    };
    
}

- (void)shareType:(int)scene {
    WXMediaMessage * message = [WXMediaMessage message];
    message.title = self.goodsDetailsModel.sku_name;
    message.description = self.goodsDetailsModel.att_title;
    
    
    UIImage *newImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:self.goodsDetailsModel.img_path];//用地址去本地找图片
    if (newImage != nil) {//如果本地有
        // newImage就是图片
        [message setThumbImage:newImage];
        WXWebpageObject * webPageObject = [WXWebpageObject object];
        webPageObject.webpageUrl =  [self getShareURL];;
        message.mediaObject = webPageObject;
        
        SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        req1.bText = NO;
        req1.message = message;
        //设置分享到朋友圈(WXSceneTimeline)、好友回话(WXSceneSession)、收藏(WXSceneFavorite)
        req1.scene = scene;
        
        [WXApi sendReq:req1 completion:^(BOOL success) {
            
        }];
    } else {//如果本地没有
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:self.goodsDetailsModel.img_path] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            [message setThumbImage:image];
            WXWebpageObject * webPageObject = [WXWebpageObject object];
            webPageObject.webpageUrl =  [self getShareURL];;
            message.mediaObject = webPageObject;
            
            SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
            req1.bText = NO;
            req1.message = message;
            //设置分享到朋友圈(WXSceneTimeline)、好友回话(WXSceneSession)、收藏(WXSceneFavorite)
            req1.scene = scene;
            
            [WXApi sendReq:req1 completion:^(BOOL success) {
                
            }];
        }];
        
    }
    

    
    
}

- (void)weiboShare {
    
    // 微博分享、需要授权
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                       @"Other_Info_1": [NSNumber numberWithInt:123],
                       @"Other_Info_2": @[@"obj1", @"obj2"],
                       @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};

    WBMessageObject *message = [WBMessageObject message];

    // 链接
    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.objectID = @"identifier1";
    webpage.title = self.goodsDetailsModel.sku_name;
    webpage.description = self.goodsDetailsModel.att_title;
    UIImage *newImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:self.goodsDetailsModel.img_path];//用地址去本地找图片
    if (newImage != nil) {//如果本地有
       webpage.thumbnailData = UIImagePNGRepresentation(newImage);
       webpage.webpageUrl = [self getShareURL];
       message.mediaObject = webpage;

       WBSendMessageToWeiboRequest *weiboRequest = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:request access_token:nil];

       weiboRequest.userInfo = nil;
       BOOL isSuccess =  [WeiboSDK sendRequest:weiboRequest];
       NSLog(@"分享是否成功 %d",isSuccess);
    } else {//如果本地没有
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:self.goodsDetailsModel.img_path] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                webpage.thumbnailData = UIImagePNGRepresentation(image);
                webpage.webpageUrl = [self getShareURL];
                message.mediaObject = webpage;

                WBSendMessageToWeiboRequest *weiboRequest = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:request access_token:nil];

                weiboRequest.userInfo = nil;
                [WeiboSDK sendRequest:weiboRequest];
        }];
        
    }
    
    
}

- (NSString *)getShareURL {
    
    NSString *details = @"";
    NSString *userCode= @"";
    if ([CommonTTool isStrNull:userModel.my_code]) {
        userCode = @"";
    }else {
        userCode = [NSString stringWithFormat:@"&code=%@",userModel.my_code];
    }
    
    if (self.goodsDetailsModel.sku_type == 1 || self.goodsDetailsModel.sku_type == 3) {
        details = [NSString stringWithFormat:@"type=1&sku_id=%@%@",self.goodsDetailsModel.sku_id,userCode];
    }
    if (self.goodsDetailsModel.sku_type == 1 && self.goodsDetailsModel.is_pt == 2) {
        details = [NSString stringWithFormat:@"type=3&sku_id=%@%@",self.goodsDetailsModel.sku_id,userCode];
    }
    
    if (self.goodsDetailsModel.sku_type == 2 || self.goodsDetailsModel.sku_type == 9) {
        details = [NSString stringWithFormat:@"type=2&sku_id=%@%@",self.goodsDetailsModel.sku_id,userCode];
    }
    
    return [NSString stringWithFormat:@"%@%@",SHARE_Detils_URL,details];
    
}

#pragma mark - 联系商家
- (void)phoneTapClick {
    
    NSString *url = [NSString stringWithFormat:@"tel://%@",self.goodsDetailsModel.busineee_tel];
    [[UIApplication   sharedApplication] openURL:[NSURL URLWithString:url]];
    
}

#pragma mark - 立即购买(需要判断)
- (void)buyBtnClick {
    
    
    if (![CommonTTool isJumpLoginVC:YES]) {
        
        return;
    }
    if (![CommonTTool isVipShow:YES]) {
        
        return;
    }
    
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    
    if (self.goodsDetailsModel.stock < self.selectoColorClassView.num) {
        SVP(@"当前选择购买数量已超出库存，请重选");
        return;
    }
    
    if (self.goodsDetailsModel.is_yk == 2 && userModel.vip_type != 2) {
        
        [CommonTTool isYinKaGoodsBuy];
        
        return;
    }
    
    if (self.goodsDetailsModel.sku_type == 3 || self.goodsDetailsModel.sku_type == 9) {
        
        ShoppingCartModel *model = [[ShoppingCartModel alloc]init];
        model.business_id = self.goodsDetailsModel.business_id;
        model.business_name = self.goodsDetailsModel.business_name;
        self.goodsDetailsModel.num = 1;
        model.shopping_car_list = @[self.goodsDetailsModel];
        
        MailConfirmOrderVC *vc = [[MailConfirmOrderVC alloc]init];
        vc.modelArray = @[model];
        vc.order_type = self.goodsDetailsModel.sku_type;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    self.isBuyBtnClick = YES;
    self.isShoppingCar = NO;
    self.isStartPt = NO;
    self.isAddPt = NO;
    self.selectoColorClassView.nextBtn.hidden = NO;
    self.selectoColorClassView.twoBgView.hidden = YES;
    [self showSelectorColorView];
    
    
}

#pragma mark - 添加到购物车
- (void)addShoppingCartBtnClick {
    
    
    if (![CommonTTool isJumpLoginVC:YES]) {
               return;
    }
    if (![CommonTTool isVipShow:YES]) {
        return;
    }
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    
    if (self.goodsDetailsModel.is_yk == 2 && userModel.vip_type != 2) {
        
        [CommonTTool isYinKaGoodsBuy];
        
        return;
    }
    self.isBuyBtnClick = NO;
    self.isShoppingCar = YES;
    self.isStartPt = NO;
    self.isAddPt = NO;
    self.selectoColorClassView.nextBtn.hidden = NO;
    self.selectoColorClassView.twoBgView.hidden = YES;
    [self showSelectorColorView];
    
}


- (MailSelectoColorClassView *)selectoColorClassView {
    
    if (!_selectoColorClassView) {
        _selectoColorClassView = [[NSBundle mainBundle] loadNibNamed:@"MailSelectoColorClassView" owner:self options:nil].lastObject;
        _selectoColorClassView.frame = CGRectMake(0, 0, KSCREEN_WIDTH, KSCREEN_HEIGHT);
        _selectoColorClassView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideSelectorColorView)];
        [_selectoColorClassView.guanbiView addGestureRecognizer:tap];
        [_selectoColorClassView.guanbiBtn addTarget:self action:@selector(hideSelectorColorView) forControlEvents:UIControlEventTouchUpInside];
        
        [_selectoColorClassView.nextBtn addTarget:self action:@selector(selectoColorBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_selectoColorClassView.buyBtn addTarget:self action:@selector(selectoColorBuyBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_selectoColorClassView.addShoppingCarBtn addTarget:self action:@selector(selectoColorAddShoppingCarBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        WeakSelf(ws);
        _selectoColorClassView.refreshMailGoodsModel = ^{
            [ws refreshMailGoodsBtnClick];
        };
        
        _wind = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _wind.windowLevel = UIWindowLevelStatusBar;

        [[UIApplication sharedApplication].keyWindow addSubview:_wind];
        [_wind addSubview:_selectoColorClassView];
        
    }
    
    return _selectoColorClassView;
    
}
#pragma mark - 选择规格开团
- (void)selectoColorBuyPtClick {
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    if (![self checkSkuAttIsSelect]) {
        
        return;
    }
    
    [self hideSelectorColorView];
    ShoppingCartModel *model = [[ShoppingCartModel alloc]init];
    model.business_id = self.goodsDetailsModel.business_id;
    model.business_name = self.goodsDetailsModel.business_name;

    model.shopping_car_list = @[self.goodsDetailsModel];

    MailConfirmOrderVC *vc = [[MailConfirmOrderVC alloc]init];
    vc.modelArray = @[model];
    vc.order_type = 4;
    vc.isAddPt = self.isAddPt;
    if (self.isAddPt) {
        vc.tg_group_id = self.addAbulkView.model.tg_group_id;
    }
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 选择规格立即购买
- (void)selectoColorBuyBtnClick {
    
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    if (self.goodsDetailsModel.stock < self.selectoColorClassView.num) {
           SVP(@"当前选择购买数量已超出库存，请重选");
           return;
    }
    
    if (![self checkSkuAttIsSelect]) {
        
        return;
    }
    
    [self hideSelectorColorView];
    ShoppingCartModel *model = [[ShoppingCartModel alloc]init];
    model.business_id = self.goodsDetailsModel.business_id;
    model.business_name = self.goodsDetailsModel.business_name;
    self.goodsDetailsModel.num = self.selectoColorClassView.num;
    model.shopping_car_list = @[self.goodsDetailsModel];
    
    MailConfirmOrderVC *vc = [[MailConfirmOrderVC alloc]init];
    vc.modelArray = @[model];
    vc.order_type = self.goodsDetailsModel.sku_type;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 选择规格添加购物车
- (void)selectoColorAddShoppingCarBtnClick  {
    
   
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    if (self.goodsDetailsModel.stock < self.selectoColorClassView.num) {
              SVP(@"当前选择购买数量已超出库存，请重选");
              return;
    }
    
    if (![self checkSkuAttIsSelect]) {
        
        return;
    }
    
    [self hideSelectorColorView];
    NSDictionary *para = @{@"type":@(self.goodsDetailsModel.sku_type),
                           @"sku_id":self.goodsDetailsModel.sku_id,
                           @"num":self.selectoColorClassView.countTF.text,
                           @"business_id":self.goodsDetailsModel.business_id,
                           @"push_res":@"1",
    };
    
    SVPShowInternetWaiting;
    [NetRequestTool postUrl:@"shoppingCar/plusOrReduceShoppingCar" parameters:para success:^(id responseObject) {
        SVP(@"加入购物车成功");

        [self performSelector:@selector(notificationShoppingCar) withObject:self afterDelay:2.0];
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
}

#pragma mark - 检验是否选择规格
- (BOOL)checkSkuAttIsSelect {
    
    if (self.selectoColorClassView.goodsAttrubuteArray.count == 0) {
        
        return YES;
    }
    NSDictionary *dict = self.selectoColorClassView.filter.currentResult;
    if (dict != nil) {
        return YES;
    }else {
        SVP(@"请选择规格");
        return NO;
    }
    
}


#pragma mark - 购物车刷新
- (void)notificationShoppingCar {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kUserAddShopingCartUpDate object:nil];
}




#pragma mark - 选择规格确定按钮
- (void)selectoColorBtnClick {
    
    if (self.isStartPt || self.isAddPt) {
        [self selectoColorBuyPtClick];
        return;
    }
    
    
    if (self.isBuyBtnClick) {
        [self selectoColorBuyBtnClick];
        return;
    }else {
        [self selectoColorAddShoppingCarBtnClick];
        return;
    }
    
}


- (MailDetailsAddBulkView *)addAbulkView {
    
    if (!_addAbulkView) {
        _addAbulkView = [[NSBundle mainBundle] loadNibNamed:@"MailDetailsAddBulkView" owner:self options:nil].lastObject;
        _addAbulkView.frame = CGRectMake(0, 0, KSCREEN_WIDTH, KSCREEN_HEIGHT);
        _addAbulkView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideAddAbulkView)];
        [_addAbulkView addGestureRecognizer:tap];
        [_addAbulkView.clossBtn addTarget:self action:@selector(hideAddAbulkView) forControlEvents:UIControlEventTouchUpInside];
        
        [_addAbulkView.addBtn addTarget:self action:@selector(requestPtListData) forControlEvents:UIControlEventTouchUpInside];
        [_wind addSubview:self.addAbulkView];
        
        
    }
    
    return _addAbulkView;
    
}

#pragma mark - 查询是否已经参与过此次拼团
- (void)requestPtListData
{
    SVPShowInternetWaiting
   // 请求列表
    [NetRequestTool postUrl:@"sku/queryPtGroupInfo" parameters:@{@"tg_group_id":self.addAbulkView.model.tg_group_id} success:^(id responseObject) {
        
        NSArray *ptList = [UserModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
        BOOL isPt = NO;
        for(UserModel *model in ptList) {
            if ([model.user_id isEqualToString:userModel.user_id]) {
                isPt = YES;
                SVP(@"您已参与此次拼团");
                return;
            }
        }
        if (!isPt) {
            [self jumpAbulkDetails];
        }
        
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
}


#pragma mark - 参与PT（需要判断）
- (void)jumpAbulkDetails {

    if (![CommonTTool isJumpLoginVC:YES]) {
        return;
    }
    
    if (![CommonTTool isVipShow:YES]) {
        return;
    }
    
    
    if (self.goodsDetailsModel.stock <= 0) {
        SVP(@"当前商品已经没有库存了");
        return;
    }
    
    
    [self  hideAddAbulkView];
    self.isBuyBtnClick = NO;
    self.isShoppingCar = NO;
    self.isStartPt = NO;
    self.isAddPt = YES;
    self.selectoColorClassView.nextBtn.hidden = NO;
    self.selectoColorClassView.twoBgView.hidden = YES;
    [self showSelectorColorView];

    
}


#pragma mark - 显示参团界面
- (void)showAddAbulkView {
    
    _wind.hidden = NO;
    self.selectoColorClassView.hidden = YES;
    self.addAbulkView.hidden = NO;
    
}

- (void)hideAddAbulkView {
    
    self.addAbulkView.hidden = YES;
    _wind.hidden = YES;
        
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            MailNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailNameCell"];
            cell.nameLabel.text = self.goodsDetailsModel.sku_name;
            cell.contentLabel.text  = self.goodsDetailsModel.att_title;
            tableView.rowHeight = UITableViewAutomaticDimension;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if(indexPath.row == 1){
            if (self.goodsDetailsModel.sku_type !=3 && self.goodsDetailsModel.sku_type != 9) {
                
                MailSelectorColorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailSelectorColorCell"];
                self.twoCell = cell;
                cell.selectGoodAttributeArray = self.selectGoodAttributeArray;
                tableView.rowHeight = UITableViewAutomaticDimension;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                
                MailSelectoStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailSelectoStoreCell"];
                    cell.businessName.text  = self.goodsDetailsModel.business_name;
                    SD_SETIMAGE_PlaceHolder(cell.imgView, self.goodsDetailsModel.head_path, @"default_image_square")

                    tableView.rowHeight = UITableViewAutomaticDimension;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    return cell;
                
            }
            
        }else {
            
            MailSelectoStoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailSelectoStoreCell"];
            cell.businessName.text  = self.goodsDetailsModel.business_name;
            SD_SETIMAGE_PlaceHolder(cell.imgView, self.goodsDetailsModel.head_path, @"default_image_square")

            tableView.rowHeight = UITableViewAutomaticDimension;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    }else if (indexPath.section == 1) {
        
        MailDetailsAlreadyAbulkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailDetailsAlreadyAbulkCell"];
        if(![CommonTTool isStrNull:self.goodsDetailsModel.pt_user_list]) {
            cell.model = self.goodsDetailsModel;
        }
        tableView.rowHeight = 60;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else if (indexPath.section == 2) {
        
        MailDetailsAddAbulkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailDetailsAddAbulkCell"];
        cell.model = self.goodsDetailsModel.pt_group_list[indexPath.row];
        cell.addBtn.tag = indexPath.row;
        [cell.addBtn addTarget:self action:@selector(addPtBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        tableView.rowHeight = 52;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    
    }else {
        
        MailGoodsContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MailGoodsContentCell"];
        cell.model = self.goodsDetailsModel;
        self.contentCell = cell;
        tableView.rowHeight = self.contentCellHeight;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
            
    }
    
    
}


#pragma mark - 参团按钮点击
- (void)addPtBtnClick:(UIButton *)btn{
    
    if (![CommonTTool isJumpLoginVC:YES]) {
        return;
    }
    
    if (![CommonTTool isVipShow:YES]) {
        return;
    }
    
    if (self.goodsDetailsModel.stock <= 0) {
           SVP(@"当前商品已经没有库存了");
           return;
    }
    
    self.addAbulkView.model = self.goodsDetailsModel.pt_group_list[btn.tag];
    [self showAddAbulkView];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.goodsDetailsModel == nil) {
        
        return 0;
    }
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        if (self.goodsDetailsModel.sku_type == 3 || self.goodsDetailsModel.sku_type == 9) {
            
            return 2;
        }
        return 3;
    }
    
    if (section == 1 && self.goodsDetailsModel.is_pt == 2) {
        if(![CommonTTool isStrNull:self.goodsDetailsModel.pt_user_list]) {
            return 1;
        }else {
            return 0;
        }
        
    }
    
    if (section == 2 && self.goodsDetailsModel.is_pt == 2) {
        if(![CommonTTool isStrNull:self.goodsDetailsModel.pt_group_list]) {
            return self.goodsDetailsModel.pt_group_list.count;
        }else {
            return 0;
        }
    }
    
    if (section == 3) {
        
        return 1;
    }
    
    return 0;
}

#pragma mark - 需要判断是否登录
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        
        if (self.goodsDetailsModel.sku_type == 3 || self.goodsModel.sku_type == 9) {
            PagingViewController *vc= [[PagingViewController alloc]init];
            vc.business_id = self.goodsDetailsModel.business_id;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
        
        if (![CommonTTool isJumpLoginVC:YES]) {
            
            return;
        }
        if (![CommonTTool isVipShow:YES]) {
            
            return;
        }
        
        if (self.goodsDetailsModel.is_yk == 2 && userModel.vip_type != 2) {
            
            [CommonTTool isYinKaGoodsBuy];
            return;
        }
        self.isBuyBtnClick = YES;
        self.isShoppingCar = NO;
        self.isStartPt = NO;
        self.isAddPt = NO;
        self.selectoColorClassView.nextBtn.hidden = YES;
        self.selectoColorClassView.twoBgView.hidden = NO;
        [self showSelectorColorView];
        
    }
    
    if (indexPath.section == 0 && indexPath.row == 2) {
        
        PagingViewController *vc= [[PagingViewController alloc]init];
        vc.business_id = self.goodsDetailsModel.business_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    if (indexPath.section == 2) {
        
//        [self showAddAbulkView];
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 2  && self.goodsDetailsModel.is_pt == 2) {
        
        MailDetailsAddAbulkHeadView *headView = [[NSBundle mainBundle] loadNibNamed:@"MailDetailsAddAbulkHeadView" owner:self options:nil].lastObject;
        
        return headView;
    }else {
        UIView *view = [[UIView alloc]init];

        view.backgroundColor = [UIColor clearColor];
        return view;
    }
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        return 10;
    }
    
    if (section == 1 && self.goodsDetailsModel.is_pt == 2) {
        if(![CommonTTool isStrNull:self.goodsDetailsModel.pt_user_list]) {
            return 10;
        }else {
            return 0.001;
        }
        
    }
    
    if (section == 2 && self.goodsDetailsModel.is_pt == 2) {
        if(![CommonTTool isStrNull:self.goodsDetailsModel.pt_group_list]) {
            if (self.goodsDetailsModel.pt_group_list.count != 0) {
                return 60;
            }
            return 0.01;
        }else {
            return 0.01;
        }
    }
    
    return 0.001;
}



- (void)showSelectorColorView {
   

    _wind.hidden = NO;
    self.selectoColorClassView.hidden = NO;
    self.addAbulkView.hidden = YES;
    self.selectoColorClassView.isBuyClik = self.isBuyBtnClick;
    self.selectoColorClassView.isShoppingCar = self.isShoppingCar;
    self.selectoColorClassView.isStartPt = self.isStartPt;
    self.selectoColorClassView.isAddPt = self.isAddPt;

    

}

- (void)hideSelectorColorView {
    
    
    _wind.hidden = YES;
    self.selectoColorClassView.hidden = YES;
    
}



- (void)refreshMailGoodsBtnClick {
    
    NSDictionary *dict =  self.selectoColorClassView.filter.currentResult;
    
    //查询新的sku_id
    NSDictionary *para = @{@"sku_code":self.goodsDetailsModel.sku_code,
                           @"sku_type":@(self.goodsDetailsModel.sku_type),
                           @"is_yk":@(self.goodsDetailsModel.is_yk),
                           @"business_id":self.goodsDetailsModel.business_id,
                           @"attribute_value_ids":dict[@"price"],
    };
    
    
    [NetRequestTool postUrl:@"sku/querySkuAttributeGoods" parameters:para success:^(id responseObject) {
        NSArray *modelArray = [MailGoodsDetailsModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
        NSMutableArray *availableSkuAtt = [NSMutableArray array];
        if (modelArray.count == 0) {
              return ;
        }

        
  
        self.goodsModel = modelArray[0];
        [self requestData];
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
}


#pragma mark - 查询商品规格属性
- (void)querySkuAttribute {
        
//    NSDictionary *para  = @{@"sku_code":self.goodsDetailsModel.sku_code,
//                            @"sku_type":@(self.goodsDetailsModel.sku_type),
//                            @"business_id":self.goodsDetailsModel.business_id,
//                            @"is_yk":@(self.goodsDetailsModel.is_yk),
//                            @"is_pt":@(self.goodsDetailsModel.is_pt),
//                            @"is_ht":@(self.goodsDetailsModel.is_ht)
//    };
    NSDictionary *para  = @{@"sku_code":self.goodsDetailsModel.sku_code,
                            @"sku_type":@(self.goodsDetailsModel.sku_type),
                            @"business_id":self.goodsDetailsModel.business_id,
                            @"is_yk":@(self.goodsDetailsModel.is_yk),
                            @"is_pt":@(self.goodsDetailsModel.is_pt),
    };
    
    
    [NetRequestTool postUrl:@"sku/querySkuAttribute" parameters:para success:^(id responseObject) {
         self.goodsAttrubuteArray = [MailGoodsAttributeModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
        self.selectoColorClassView.goodsAttrubuteArray  = self.goodsAttrubuteArray;
        
        
    } failure:^(NSInteger statusCode) {
        
        
    } finish:^{
        
    }];
    

    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self hideAddAbulkView];
    [self hideSelectorColorView];
}


@end
